package controllers

import (
	"fly/global"
	"fly/helper"
	"fly/models"
	"fly/req"
	"fly/resp"
	"fly/schema"
	"fly/service"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/condition"
	"github.com/duke-git/lancet/v2/convertor"
	"net/url"
)

// SysDictController 启动字典
type SysDictController struct {
	BaseController
	SysDictService service.SysDictService
	SysUserService service.SysUserService
}

// GetDict ...
// @Title 字典
// @Description 根据id获取字典
// @Param	id path  string	true "id的key"
// @Param	token header  string false "授权Token"
// @Success 200 {object} resp.SysDictResp
// @router /:id [get]
func (c *SysDictController) GetDict() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	con, err := models.GetSysDictionaryById(id)
	c.CheckAssertAbort(con, "未找到资源")
	r := resp.SysDictResp{}
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&r, con))
	c.Success(r)
}

// GetByCode ...
// @Title 字典
// @Description 根据code获取字典
// @Param	code path  string	true "code"
// @Param	token header  string false "授权Token"
// @Success 200 {object} []resp.SysDictResp
// @router /code/:code [get]
func (c *SysDictController) GetByCode() {
	var list []*models.SysDictionary
	_, err := orm.NewOrm().QueryTable(new(models.SysDictionary)).Filter("dic_code",
		c.Ctx.Input.Param(":code")).Filter("status__gte", schema.Enabled).Filter("enabled__gte", schema.Enabled).All(&list)
	c.CheckRespErrorAbort(err)
	var arr []resp.SysDictResp
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&arr, list))
	c.Success(arr)
}

// GetByCodeKey ...
// @Title 字典
// @Description 根据code/key获取字典
// @Param	code path  string	true "code"
// @Param	key path  string	true "key"
// @Param	token header  string false "授权Token"
// @Success 200 {object} resp.SysDictResp
// @router /code/:code/:key [get]
func (c *SysDictController) GetByCodeKey() {
	m, err := c.SysDictService.GetDictByCodeKey(c.Ctx.Input.Param(":code"), c.Ctx.Input.Param(":key"))
	c.CheckRespErrorAbort(err)
	r := resp.SysDictResp{}
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&r, m))
	c.Success(r)
}

// GetByParentCode ...
// @Title 字典
// @Description 根据parentCode获取字典
// @Param	code path  string	true "code"
// @Param	token header  string false "授权Token"
// @Success 200 {object} []resp.SysDictResp
// @router /parent/:code [get]
func (c *SysDictController) GetByParentCode() {
	code := c.Ctx.Input.Param(":code")
	var list []*models.SysDictionary
	_, err := orm.NewOrm().QueryTable(new(models.SysDictionary)).Filter("parent_code",
		code).Filter("status__gte", schema.Enabled).Filter("enabled__gte", schema.Enabled).All(&list)
	c.CheckRespErrorAbort(err)
	var arr []resp.SysDictResp
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&arr, list))
	c.Success(arr)
}

// AddDict ...
// @Title 添加字典
// @Description 添加一个新字典
// @Param token header  string	false "授权Token"
// @Param body body req.AddSysDictReq true "添加字典内容"
// @Success 200 {object} resp.SysDictResp
// @router /save [post]
func (c *SysDictController) AddDict() {
	con := req.AddSysDictReq{}
	err := c.BindJSON(&con)
	c.CheckReqErrorAbort(err)
	c.ValidReqParams(&con)
	mConfig := models.SysDictionary{}
	c.CheckRespErrorAbort(convertor.CopyProperties(&mConfig, con))
	if con.Id > 0 {
		old, _ := models.GetSysDictionaryById(con.Id)
		c.CheckReqErrorAbort(helper.RequireTrue(old != nil, "未找到资源"))
		_ = helper.CopyOut(old, con)
		err = models.UpdateSysDictionaryById(old, c.GetReqUserId())
	} else {
		_, err = models.AddSysDictionary(&mConfig, c.GetReqUserId())
	}
	c.CheckRespErrorAbort(err)
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheSimple, con.Id))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheValue, con.Id))
	r := resp.SysDictResp{}
	_ = resp.Copy2TimeResp(&r, mConfig)
	c.Success(r)
}

// Index ...
// @Title 字典查询
// @Description 字典查询
// @Param token header  string	false "授权Token"
// @Param page query  string false "当前页"
// @Param pageSize query  string false "分页大小"
// @Param dicValue query  string false "查询值"
// @Param dicKey query  string false "查询key"
// @Param dicCode query  string false "查询Code"
// @Param enabled query  string false "查询状态"
// @Success 200 {object} service.Pagination
// @router / [get]
func (c *SysDictController) Index() {
	params, _ := url.ParseQuery(c.Ctx.Request.URL.RawQuery)
	data, pagination := c.SysDictService.GetPaginateData(params)
	var list []resp.SysDictResp
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&list, &data))
	pagination.List = list
	c.Success(pagination)
}

// Enable 停用启用
// @Title Enable
// @Description 停用启用
// @Param token header  string	false "授权Token"
// @Param path id int true "字典id"
// @Success 200 {int} "id"
// @router /enable/:id [put]
func (c *SysDictController) Enable() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	m, err := models.GetSysDictionaryById(id)
	c.CheckAssertAbort(m, "资源不存在")
	m.Enabled = condition.TernaryOperator(m.Enabled == schema.Disable, schema.Enabled, schema.Disable)
	c.CheckRespErrorAbort(models.UpdateSysDictionaryById(m, c.GetReqUserId()))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheSimple, id))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheValue, id))
	c.Ok()
}

// Del ...
// @Title 删除
// @Description 删除字典
// @Param token header  string	false "授权Token"
// @Param path id int true "字典id"
// @Success 200 {int} "id"
// @router /:id [delete]
func (c *SysDictController) Del() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	c.CheckReqErrorAbort(helper.RequireTrue(c.SysUserService.IsSuperAdminUser(c.GetReqUserId()), "超级管理员才能操作"))
	aircraftCount, _ := orm.NewOrm().QueryTable(new(models.Aircraft)).Filter("type_dict_id", id).Count()
	c.CheckReqErrorAbort(helper.RequireTrue(aircraftCount == 0, "该字典还有飞机关联使用"))
	airportCount, _ := orm.NewOrm().QueryTable(new(models.Airport)).Filter("type_dict_id", id).Count()
	c.CheckReqErrorAbort(helper.RequireTrue(airportCount == 0, "该字典还有机场关联使用"))
	taskCount, _ := orm.NewOrm().QueryTable(new(models.FlightTask)).Filter("task_scene_id", id).Count()
	c.CheckReqErrorAbort(helper.RequireTrue(taskCount == 0, "该字典还有飞机任务关联使用"))
	c.CheckRespErrorAbort(models.DeleteSysDictionary(id))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheSimple, id))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheValue, id))
	c.Success(id)
}

// Destroy ...
// @Title 禁用
// @Description 相当于逻辑删除
// @Param token header  string	false "授权Token"
// @Param path id int true "字典id"
// @Success 200 {int} "id"
// @router /destroy/:id [put]
func (c *SysDictController) Destroy() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	c.CheckRespErrorAbort(models.DestroySysDictionary(id, c.GetReqUserId()))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheSimple, id))
	_ = global.DelCache(fmt.Sprintf(service.DictionaryCacheValue, id))
	c.Success(id)
}
